﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Harkon.AppServer.cOne.DataAccess
{
    public abstract class Entity
    {
        protected EntityMeta Meta;
        protected IDictionary<string, EntityProperty> Properties = new Dictionary<string, EntityProperty>();

        public static ENTITY CreateNew<ENTITY>() where ENTITY : Entity, new()
        {
            ENTITY result = new ENTITY();

            object[] customClassAttributes = typeof(ENTITY).GetCustomAttributes(true);
            if (customClassAttributes != null && customClassAttributes.Count() != 0)
            {
                var entityProperty = customClassAttributes.Where(x => x is EntityAttribute).Cast<EntityAttribute>().First();
                if (entityProperty != null)
                    result.Meta = new EntityMeta { TableName = entityProperty.TableName };
            }

            var properties = typeof(ENTITY).GetProperties();
            foreach (var property in properties)
            {
                object[] customAttributes = property.GetCustomAttributes(true);
                if (customAttributes != null && customAttributes.Count() != 0)
                {
                    var entityProperty = customAttributes.Where(x => x is DataAccessAttribute).Cast<DataAccessAttribute>().First();
                    if (entityProperty != null)
                    {
                        EntityProperty newEntityProperty = entityProperty.CreateEntityProperty();
                        result.Properties.Add(newEntityProperty.Name, newEntityProperty);
                    }
                }

            }

            return result;
        }

        public override string ToString()
        {
            string result = "[" + Meta.TableName + " ";
            bool first = true;
            foreach (var property in Properties)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    result += ", ";
                }
                result += property.ToString();
            }
            return result + "]";
        }
    }
}
